import { withPluginApi } from "discourse/lib/plugin-api";

export default {
  name: "nav-links-component",

  initialize() {
    withPluginApi("0.8", (api) => {
      const itemsSetting = settings.Nav_links;
      const items = itemsSetting.split("|").map((item) => item.trim());
      const username = api.getCurrentUser()?.username;

      for (const item of items) {
        
        // 如果用户未登录，则不显示mine
        if (item.includes("mine") && !api.getCurrentUser()) {
            continue;
        }
        const splitSec = item.split(";").map((section) => section.trim());
        const filter = I18n.t(themePrefix( "nav_links." + splitSec[0])) || splitSec[0];
        const filterDasherized = splitSec[0].replace(/\s+/g, "-").toLowerCase();
        const title = I18n.t(themePrefix( "nav_links." + splitSec[1])) || splitSec[1];
        // 如果location中有{username}，则替换为当前用户的username
        const location = splitSec[2].includes("{username}") ? splitSec[2].replace("{username}", username) : splitSec[2];

        api.addNavigationBarItem({
          name: `custom_${filterDasherized}`,
          displayName: filter,
          title,
          href: location,
          // 如果是第一个item，且当前url为根目录，则显示active
          forceActive: (category, args, router) => 
            router.currentURL.includes(location) || ((router.currentURL == "/" || router.currentURL.includes("/c")) && item == items[0])
        });
      }
    });
  },
};